from flask import render_template, jsonify, request
from app import app, socketio
from app.mqtt_client import sensor_data, device_status, manual_control_device

@app.route('/')
def index():
    """主页路由"""
    return render_template('index.html', sensor_data=sensor_data, device_status=device_status)

@app.route('/api/sensor_data')
def get_sensor_data():
    """获取传感器数据的API"""
    return jsonify(sensor_data)

@app.route('/api/device_status')
def get_device_status():
    """获取设备状态的API"""
    return jsonify(device_status)

@app.route('/api/control_device', methods=['POST'])
def control_device():
    """控制设备的API"""
    try:
        control_data = request.json
        success, message = manual_control_device(control_data)
        return jsonify({'success': success, 'message': message})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})

# SocketIO事件处理
@socketio.on('connect')
def handle_connect():
    """处理客户端连接事件"""
    print('客户端已连接')
    # 发送当前数据给新连接的客户端
    socketio.emit('sensor_data_update', sensor_data)
    socketio.emit('device_status_update', device_status)

@socketio.on('disconnect')
def handle_disconnect():
    """处理客户端断开连接事件"""
    print('客户端已断开连接')

@socketio.on('control_device')
def handle_control_device(data):
    """处理设备控制事件"""
    success, message = manual_control_device(data)
    return {'success': success, 'message': message}